package com.fivefox.document.table.dto;


import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 多维表格 数据修改模板
 *
 * @author lirenqi
 */
public class TableRecordsUpdateDTO {


    class UpdateRecords{
        /** 一条记录的唯一标识，通过此标识来修改记录  */
        public String record_id;

        /**
         * 数据表的字段，即数据表的列
         */
        public JSONObject fields;

        public UpdateRecords() {
        }

        public UpdateRecords(String recordId, JSONObject fields) {
            this.record_id = recordId;
            this.fields = fields;
        }

        public String getRecordId() {
            return record_id;
        }

        public void setRecordId(String record_id) {
            this.record_id = record_id;
        }

        public JSONObject getFields() {
            return fields;
        }

        public void setFields(JSONObject fields) {
            this.fields = fields;
        }

        @Override
        public String toString() {
            return "UpdateRecords{" +
                    "recordId='" + record_id + '\'' +
                    ", fields=" + fields +
                    '}';
        }
    }

    public List<UpdateRecords> records;

    public TableRecordsUpdateDTO() {
        /** 初始化资源 */
        records=new ArrayList<>();
    }

    public TableRecordsUpdateDTO(List<UpdateRecords> records) {
        this.records = records;
    }

    public List<UpdateRecords> getRecords() {
        return records;
    }

    public void setRecords(List<UpdateRecords> records) {
        this.records = records;
    }

    public void addTableItem(String recordId,JSONObject fields){
        UpdateRecords updateRecords=new UpdateRecords(recordId,fields);
        this.getRecords().add(updateRecords);
    }


    /**
     * 对list数据中进行分片
     *
     * @param fragment 指定集合每份元素数量
     * @return 返回当前类的集合
     */
    public List<TableRecordsUpdateDTO> getListFragment(int fragment) {
        /** 为空则终止往下执行 */
        if (this.records == null) {
            return null;
        }
        if (this.records.size() == 0) {
            return null;
        }
        /** 返回结果 */
        List<TableRecordsUpdateDTO> tableRecordsUpdateDTOList = new ArrayList<>();
        /** 分片结果 */
        List<List<UpdateRecords>> arrayList = ListUtils.partition(this.records, fragment);
        /** 将分片结果添加至对象集合中，方便执行新增操作 */
        for (List<UpdateRecords> jsonObjectList : arrayList) {
            tableRecordsUpdateDTOList.add(new TableRecordsUpdateDTO(jsonObjectList));
        }
        return tableRecordsUpdateDTOList;
    }

    @Override
    public String toString() {
        return "TableRecordsUpdateDTO{" +
                "records=" + records +
                '}';
    }
}
